package com.action.pc.merchant;

import com.bean.Member;
import com.bean.Merchant;
import com.bean.Sys_user;
import com.common.BaseAction;
import com.common.ModelAndJson;
import com.github.pagehelper.Page;
import com.service.member.MemberService;
import com.service.merchant.MerchantService;
import com.util.Config;
import com.util.UploadUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lvjianqing on 2017/9/10.
 */
@Controller
@RequestMapping("merchant")
public class MerchantAction extends BaseAction {
    Logger log = Logger.getLogger(MerchantAction.class);
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MemberService memberService;

    @RequestMapping("list")
    public ModelAndView list(ModelMap modelMap, MerchantVo vo) {
        int pageNum = vo.getPageNumInt();
        int pageSize = vo.getPageSizeInt();
        HashMap<String, Object> paraMap = new HashMap<>();
        filterParaMap(paraMap);
        paraMap.put("mtname", vo.getMtname());
        paraMap.put("contact", vo.getContact());
        paraMap.put("tel", vo.getTel());
        paraMap.put("landline", vo.getLandline());
        paraMap.put("starttime", vo.getStarttime());
        paraMap.put("endtime", vo.getEndtime());
        Page page = merchantService.findByPage(pageNum, pageSize, paraMap);
        modelMap.put("page", page);
        modelMap.put("pages", page.getPages());
        modelMap.put("pageNum", page.getPageNum());
        modelMap.put("pageSize", page.getPageSize());
        modelMap.put("vo", vo);
        return new ModelAndView("/pc/merchant_list", modelMap);
    }

    @RequestMapping("modify")
    public ModelAndView modify(HttpServletRequest request, ModelMap modelMap, MerchantVo vo) {
        Integer id = vo.getId();
        Merchant merchant = new Merchant();
        if (id != null) {
            merchant = merchantService.findMerchantById(id);
        }
        modelMap.put("merchant", merchant);
        return new ModelAndView("/pc/merchant_modify", modelMap);
    }

    @RequestMapping("save")
    public ModelAndView save(HttpServletRequest request, ModelMap modelMap, MerchantVo vo, @RequestParam MultipartFile file) {
        String img = null;
        try {
            img = UploadUtil.uploadImg(file, request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Merchant merchant = new Merchant();
        merchant.setMtimg(img);
        merchant.setId(vo.getId());
        merchant.setMtname(vo.getMtname());
        merchant.setContact(vo.getContact());
        merchant.setTel(vo.getTel());
        merchant.setLandline(vo.getLandline());
        merchant.setCityid(vo.getCityid());
        merchant.setClearprop(vo.getClearprop());
        if (vo.getProvincename() != null && "请选择".equals(vo.getProvincename())) {
            vo.setProvincename("");
        }
        merchant.setProvincename(vo.getProvincename());
        if (vo.getCityname() != null && "请选择".equals(vo.getCityname())) {
            vo.setCityname("");
        }
        merchant.setCityname(vo.getCityname());
        if (vo.getRegionname() != null && "请选择".equals(vo.getRegionname())) {
            vo.setRegionname("");
        }
        merchant.setRegionname(vo.getRegionname());
        merchant.setLng(vo.getLng());
        merchant.setLat(vo.getLat());
        merchantService.saveMerchant(merchant);
        return new ModelAndView("redirect:/merchant/list.htm", modelMap);
    }

    @ExceptionHandler
    public ModelAndView doException(Exception e, HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (e instanceof MaxUploadSizeExceededException) {
            long maxSize = ((MaxUploadSizeExceededException) e).getMaxUploadSize();
            map.put("error", "上传文件太大，不能超过" + maxSize / 1024 + "k");
        } else if (e instanceof RuntimeException) {
            map.put("error", "未选中文件");
        } else {
            map.put("error", "上传失败");
        }
        return new ModelAndView("upload", map);

    }

    @RequestMapping("active")
    @ResponseBody
    public String active(HttpServletRequest request, ModelAndJson modelMap, MerchantVo vo) {
        Integer id = vo.getId();
        Integer enable = vo.getEnable();
        if (id != null && enable != null) {
            Merchant merchant = new Merchant();
            merchant.setId(id);
            merchant.setEnable(enable);
            merchantService.updateByPrimaryKeySelective(merchant);
        }
        modelMap.setTrue("设置成功");
        return modelMap.toString();
    }

    @RequestMapping("qrcode")
    public ModelAndView qrcode(HttpServletRequest request, ModelMap modelMap, MerchantVo vo) {
        Integer id = null;
        Merchant merchant = new Merchant();
        Long jsid = getJsid();
        if (jsid == 2 || jsid == 3) {
            id = vo.getId();
        } else if (jsid == 4) {
            Sys_user user = getSysUser();
            id = user.getMerchantid();
        }
        if (id != null) {
            merchant = merchantService.findMerchantById(id);
            if (merchant != null && merchant.getMemberid() != null) {
                Member member = memberService.selectByPrimaryKey(merchant.getMemberid());
                if (member != null) {
                    modelMap.put("member", member);
                }
            }
        }
        modelMap.put("merchant", merchant);
        modelMap.put("qrContent", getQRContent(merchant.getId(),merchant.getCityid()));
        return new ModelAndView("/pc/merchant_qrcode", modelMap);
    }

    private String getQRContent(Integer mid,Integer cid) {
        String appid = Config.getString("wx.appid");
        String domain = Config.getString("domain");
        String url = domain + "/wx/bindmerchant.htm?cid="+cid+"&mid="+mid;
        String str = null;
        try {
            str = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + URLEncoder.encode(url, "utf-8") + "&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
            str = URLEncoder.encode(str,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 会员解除绑定
     * @param model
     * @return
     */
    @RequestMapping("relieve")
    @ResponseBody
    public String relieve(ModelAndJson model){
        Sys_user user = getSysUser();
        Merchant merchant = merchantService.findMerchantById(user.getMerchantid());
        if(merchant!=null && merchant.getMemberid()!=null){
            Member member = memberService.selectByPrimaryKey(merchant.getMemberid());
            if(member!=null) {
                merchant.setMemberid(null);
                merchantService.updateByPrimaryKey(merchant);
                member.setIsmerchant((byte) 0);
                member.setMerchantid(null);
                memberService.updateByPrimaryKey(member);
            }else{
                model.setFalse("-1","解除失败");
            }
        }else{
            model.setFalse("-1","解除失败");
        }
        return model.toString();
    }

    @RequestMapping("searchMerchant")
    @ResponseBody
    public String searchMerchant(String mtname) {
        return "<option>111</option><option>222</option><option>333</option>";
    }
}
